package com.chenyi.common.utils;

import com.chenyi.common.constant.Constants;
import com.chenyi.common.core.domain.model.LoginUser;
import com.chenyi.common.core.redis.RedisCache;
import com.chenyi.common.exception.BadRequestException;
import com.chenyi.common.utils.ip.AddressUtils;
import com.chenyi.common.utils.ip.IpUtils;
import com.chenyi.common.utils.spring.SpringUtils;
import com.chenyi.common.utils.uuid.IdUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.context.request.RequestAttributes;

import java.util.Calendar;
import java.util.concurrent.TimeUnit;

/**
 * ApiUtils：
 *
 * @author WangKh
 */
public class ApiUtils {

    /**
     * 获取用户信息
     *
     * @return
     */
    public static LoginUser getApiUser() {
        try {
            return (LoginUser)ServletUtils.getRequestAttributes().getAttribute("user", RequestAttributes.SCOPE_REQUEST);
        } catch (Exception e) {
            throw new BadRequestException(HttpStatus.UNAUTHORIZED, "获取用户信息异常");
        }
    }

    public static String getUserType() {
        return getApiUser().getUserType();
    }

    public static Long getUserId() {
        return getApiUser().getUser().getUserId();
    }

    public static boolean getIsLogin() {
        try {
            return getApiUser() == null ? false : true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }


}
